package com.example.administrator.znjt.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.widget.GridView;

import com.android.volley.VolleyError;
import com.example.administrator.znjt.R;
import com.example.administrator.znjt.adapter.EnvironmentalAdapter;
import com.example.administrator.znjt.bean.DataStack;
import com.example.administrator.znjt.data.EnvironmentalDBHelper;
import com.example.administrator.znjt.util.MyVolley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.administrator.znjt.data.EnvironmentalDBHelper.TABLE_NAME;

/**
 * Created by Administrator on 2017/5/10.
 */

public class EnvironmentalActivity extends Activity {

    private EnvironmentalDBHelper environmentalDBHelper;
    private SQLiteDatabase sqLiteDatabase;

    private static final long TIME=50000;
    private static final long UPDATE_TIME = 5000;
    private static final long MINUTE_TIME=60000;

    private GridView gridView;
    private EnvironmentalAdapter environmentalAdapter;
    private JSONObject object;

    private List<EnvironmentalAdapter.Bean> beanList = new ArrayList<>();

    private String[] title = {
            "空气温度", "空气湿度", "光照", "CO2", "PM2.5", "道路状况"
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.environmental_gridview);
        MyVolley.init(this);
        init();
        handler.post(postRunnable);
        handler.post(dataRunnable);
    }

    public void init() {
        environmentalDBHelper = new EnvironmentalDBHelper(this);
        gridView = (GridView) findViewById(R.id.gridview);
        environmentalAdapter = new EnvironmentalAdapter(beanList, this);
        gridView.setAdapter(environmentalAdapter);
        //添加数据到list
        for (int i = 0; i < title.length; i++) {
            EnvironmentalAdapter.Bean bean = environmentalAdapter.new Bean();
            bean.setTitle(title[i]);
            beanList.add(bean);
        }
    }

    Handler handler = new Handler();
    Runnable postRunnable = new Runnable() {
        @Override
        public void run() {
            getpost();
            post1();
            handler.postDelayed(postRunnable, UPDATE_TIME);
        }
    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(postRunnable);
        handler.removeCallbacks(dataRunnable);
        super.onDestroy();
    }

    public void getpost() {
        String url = "http://192.168.1.101:8080/transportservice/type/jason/action/GetAllSense.do";
        MyVolley.Post(url, null, new MyVolley.OnRequestListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    String string = result.getString("serverinfo");
                    object = new JSONObject(string.replace("\n", "").replace("\\", ""));
                    beanList.get(0).setValue(object.getInt("temperature"));
                    beanList.get(1).setValue(object.getInt("humidity"));
                    beanList.get(2).setValue(object.getInt("LightIntensity"));
                    beanList.get(3).setValue(object.getInt("co2"));
                    beanList.get(4).setValue(object.getInt("pm2.5"));
                    environmentalAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    //                   e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {
                System.out.println(error);
            }
        });
    }

    public void post1() {
        String url = "http://192.168.1.101:8080/transportservice/type/jason/action/GetRoadStatus.do";
        Map map = new HashMap();
        map.put("RoadID", 1);
        JSONObject jsonObject = new JSONObject(map);
        MyVolley.Post(url, jsonObject, new MyVolley.OnRequestListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    String string = result.getString("serverinfo");
                    object = new JSONObject(string.replace("\n", ""));
                    beanList.get(5).setValue(object.getInt("Status"));
                    environmentalAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
//                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {
                System.out.println(error);
            }
        });
    }


    Runnable dataRunnable =new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(dataRunnable,MINUTE_TIME);
            //复制当前传感器值
            List<EnvironmentalAdapter.Bean> list = new ArrayList<>();
            list.addAll(beanList);
            //将当前传感器值压入栈
            invokeStack( list);
            //保存到数据库
            insert(list);
        }
    };

    private void invokeStack( List<EnvironmentalAdapter.Bean> list) {
        DataStack dataStack = new DataStack();
        for (EnvironmentalAdapter.Bean bean : list) {
            dataStack.push(bean);//入栈
            if(dataStack.size() == DataStack.MAX_SIZE){//当栈满时，计算平均值
                int sum =0;
                while (dataStack.size()>0){
                    sum += dataStack.pop().getValue();//出栈
                }
                bean.setValue(sum/DataStack.MAX_SIZE);
            }
        }
    }

    public void insert(List<EnvironmentalAdapter.Bean> list){
        ContentValues contentValues = new ContentValues();
        for (int i=0;i<title.length;i++) {//添加  "空气温度", "空气湿度", "光照", "CO2", "PM2.5", "道路状况"
            sqLiteDatabase = environmentalDBHelper.getWritableDatabase();
            contentValues.put(EnvironmentalDBHelper.KEY_SET[i],list.get(i).getValue());
        }
        contentValues.put(EnvironmentalDBHelper.KEY_TIME,System.currentTimeMillis());//添加当前时间
        sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
    }

}
